<template>
  <div class="main" style="font-size: 12px;">
    <div class="header">
      <div class="search">

        <el-input style="width: 300px;" size='small' placeholder="请输入盘点单名" v-model="params.name">
          <template slot="prepend">名称</template>
        </el-input>
        <el-select v-model="params.warehouseId" size='small' style='margin: 0 20px;' placeholder="请选择仓库">
          <el-option v-for="item in warehouseList" :key="item.value" :label="item.warehouseName"
                     :value="item.warehouseId">
          </el-option>
        </el-select>
        <el-date-picker v-model="params.time" size='small' type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" @change="chooseTime">
        </el-date-picker>
        <el-button @click="searchGetCheckList"
                   size='small'
                   style='background-color: #ff6a00;color:white;margin-left:20px'>查询
        </el-button>
      </div>
      <div>
        <el-button size='small' style='background-color: #ff6a00;color:white' @click="addCheck">新增</el-button>
      </div>
    </div>
    <!-- 盘点表   -->
    <div class="mainTable">
      <el-table :height="maxHeight + 'px'" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                v-loading="loading" :data="checkList.list" border style="width: 100%;font-size: 12px;"
                :headerCellStyle="{ 'textAlign': 'center', 'fontWeight': '400', 'background': '#ff6a00', 'color': 'white' }"
                :cellStyle="{ 'textAlign': 'center','fontSize': '12px' }">
        <el-table-column prop="checkId" label="盘点单号" min-width="140px"></el-table-column>
        <el-table-column prop="checkName" label="盘点单名" min-width="140px"></el-table-column>
        <el-table-column prop="warehouse.warehouseName" min-width="80px" label="仓库"></el-table-column>
        <el-table-column label="盘点明细" width="600px">
          <template slot-scope="props">
            <el-table :data="props.row.checkDetailList" border
                      maxHeight="300px"
                      :headerCellStyle="{ 'textAlign': 'center', 'fontWeight': '400', }"
                      :cellStyle="{ 'textAlign': 'center' ,'font-size':'12px'}">
              >
              <el-table-column prop="materialId" min-width="100" label="材料编码"></el-table-column>
              <el-table-column prop="materialName" min-width="150" label="材料名称"></el-table-column>
              <el-table-column prop="price" min-width="80" label="成本价"></el-table-column>
              <el-table-column min-width="80" label="数量">
                <template slot-scope="props">
                  <el-link :type="props.row.count < 0 ? 'danger' : 'success'">{{ props.row.count }}</el-link>
                </template>
              </el-table-column>
              <el-table-column prop="totalPrice" width="100" label="差价"></el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="sumXPrice" label="差价总计" width="100"></el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.checkStatus == 0" type="danger" size="mini">待处理</el-tag>
            <el-tag size="mini" v-if="scope.row.checkStatus == 1" type="success">已通过</el-tag>
            <el-tag size="mini" v-if="scope.row.checkStatus == 2" type="info">已驳回</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="原因" width="200"></el-table-column>
        <el-table-column prop="remark" label="备注" width="200"></el-table-column>
        <el-table-column prop="voucher" label="凭证" min-width="80px">
          <template slot-scope="scope">
            <el-image v-for='(v, i) in scope.row.checkVouchersList' :key="i" style="width: 50px; height: 50px"
                      ref="preview" :src="v" :preview-src-list="scope.row.checkVouchersList">

            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="checkTime" label="盘点日期" width="120"></el-table-column>
        <el-table-column fixed="right" label="操作" width="100"
                         v-if="userName == 'admin' || userName=='王伯维'||userName=='沈旭滨'||userName=='王健'||userName=='袁文典'">
          <template slot-scope="data">
            <div>
              <el-link style="color:#ff6a00" @click="changeProcureInfo(data.row)">变更明细</el-link>
            </div>
            <div>
              <el-link type="success" @click="updateStatus(true, data.row)">通过</el-link>
              <el-link type="danger" style="margin-left: 5px" @click="updateStatus(false, data.row)">驳回</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style='margin-top:20px' align="right" @size-change="handleCheckSizeChange"
                     @current-change="handleCheckCurrentChange" :current-page="checkList.currentPage"
                     :page-sizes="[10,20,30,40,50]" layout="total, sizes, prev, pager, next, jumper"
                     :total="checkList.count">
      </el-pagination>
    </div>
    <!-- 新增 -->
    <el-dialog title="新增盘点单" :visible.sync="dialogVisible" width="70%" :before-close="handleClose">
      <div style="" class="createInfo">
        <div>
          <div>名称</div>
          <el-input placeholder="请输入盘点单名" v-model="createdInfo.name" clearable>

          </el-input>
        </div>
        <div>
          <div>
            仓库
          </div>
          <el-select v-model="createdInfo.warehouseId" clearable style='width: 100%;' placeholder="请选择仓库">
            <el-option v-for="item in warehouseList" :key="item.value" :label="item.warehouseName"
                       :value="item.warehouseId">
            </el-option>
          </el-select>
        </div>
        <div>
          <div>盘点日期</div>
          <el-date-picker style="width: 100%;" v-model="createdInfo.time" type="date" placeholder="选择日期">
          </el-date-picker>
        </div>
        <div>
          <div>原因
          </div>
          <el-input placeholder="请输入盘点原因" v-model="createdInfo.reason" clearable>

          </el-input>
        </div>
        <div>
          <div>备注</div>
          <el-input placeholder="请输入备注" rows='8' type="textarea" v-model="createdInfo.remark">

          </el-input>
        </div>
        <div>
          <div>凭证</div>
          <div>
            <rayUpload @url="getImageUrl"></rayUpload>
          </div>
        </div>
      </div>
      <div style="margin-top: 20px;">
        <div style='margin-bottom: 10px'><span style="color:red;">*</span>请选择先选择盘点仓库</div>
        <el-table :height="300" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                  v-loading="loading" :data="materialList" border style="width: 100%"
                  :headerCellStyle="{ 'textAlign': 'center', 'fontWeight': '400', 'background': '#ff6a00', 'color': 'white' }"
                  :cellStyle="{ 'textAlign': 'center','fontSize': '12px' }">

          <el-table-column prop="materialId" label="材料编码" min-width="120"></el-table-column>
          <el-table-column prop="material.materialName" label="材料名称" min-width="280"></el-table-column>
          <el-table-column prop="material.norm" label="规格" min-width="120"></el-table-column>
          <el-table-column prop="material.color" label="颜色" min-width="100"></el-table-column>
          <el-table-column prop="material.unit" label="单位" min-width="100"></el-table-column>
          <el-table-column prop="material.price" label="成本价" min-width="100"></el-table-column>
          <el-table-column prop="material.salePrice" label="销售价" min-width="100"></el-table-column>
          <el-table-column label="数量" min-width="200">
            <template slot-scope="scope">
              <el-input-number size='mini' v-model.trim="scope.row.count"></el-input-number>
            </template>
          </el-table-column>

        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="addCheckConfirm">确 定</el-button>
            </span>
    </el-dialog>
    <changeBox @close="changeBoxClose" apiName="changeSelectChangeDetailList" v-if="changeBoxStatus"
               :targetId="targetId">
    </changeBox>
  </div>
</template>
<script>
import dayjs from "dayjs";
import Decimal from "decimal.js";

import tableMixins from "@/mixins/tableMixins.vue";
import rayUpload from '@/RayComponents/rayUpload.vue'
import changeBox from '@/RayComponents/materialChange.vue'
import quinn from "@/utils/quinn";

export default {
  name: "checkList",
  mixins: [tableMixins],
  meta: { title: "盘点列表", icon: "el-icon-edit-outline", sort: 50, authority: 115 },
  components: {
    rayUpload,
    changeBox
  },
  data() {
    return {
      apiName: "classificationMaterialList",
      targetId: '',
      changeBoxStatus: false,
      checkVouchersList: [],
      loading: false,
      warehouseList: [],
      dialogVisible: false,
      userName: '',
      params: {
        name: '',
        startTime: '',
        endTime: '',
        warehouseId: ''
      },
      previewImg: [],
      createdInfo: {
        time: '',
        warehouseId: '',
        name: '',
        remark: '',
        reason: '',
        checkVouchers: ''
      },
      checkList: {
        list: [],
        count: 100,
        currentPage: 1,
        pageSize: 10,
        pageNumber: 1
      },
      materialList: [],
      maxHeight: 0
    };
  },
  mounted() {

    this.userName = quinn.getStorage("userDatav3").userName
    this.$nextTick(() => {
      this.maxHeight = window.innerHeight - 240;
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.maxHeight = window.innerHeight - 240;
      })
    }
  },
  watch: {
    "$store.state.warehouseList": {
      handler(newVal) {
        this.warehouseList = newVal

      },
      deep: true,
      immediate: true
    },
    'createdInfo.warehouseId': {
      handler(newVal, oldVal) {
        if (newVal && newVal !== oldVal) {
          this.getMaterialList();
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getCheckList();
  },
  methods: {
    changeBoxClose(e) {
      this.changeBoxStatus = e;
    },
    changeProcureInfo(info) {
      this.targetId = info.checkId;
      this.changeBoxStatus = true;
    },
    chooseTime(e) {
      this.params.startTime = dayjs(e[0]).format("YYYY-MM-DD");
      this.params.endTime = dayjs(e[1]).format("YYYY-MM-DD");
    },
    getCheckList() {
      this.loading = true
      this.$api.checkCheckList({
        pageSize: this.checkList.pageSize,
        pageNumber: this.checkList.pageNumber,
        checkName: this.params.name,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
        warehouseId: this.params.warehouseId
      }).then(res => {
        this.loading = false;
        this.checkList.count = res.count;
        res.rows.map(el => {
          el.checkDetailList.map(k => {
            k.totalPrice = Decimal(k.price).mul(Decimal(k.count)).toNumber();
            if (el.checkVouchers) {
              el.checkVouchersList = [this.host + el.checkVouchers]
            } else {
              el.checkVouchersList = []
            }
          })
        })
        this.checkList.list = res.rows;
      })

    },
    getImageUrl(e) {
      this.createdInfo.checkVouchers = e;
    },
    getMaterialList() {
      this.$api.inventoryInventoryList({
        pageSize: 100000,
        pageNumber: 1,
        warehouseId: this.createdInfo.warehouseId
      }).then(res => {
        res.rows.map(el => {
          el.count = 0
        })
        this.materialList = res.rows;
      })
    },
    searchGetCheckList() {
      this.checkList.pageNumber = 1;
      this.getCheckList();
    },
    addCheck() {
      this.dialogVisible = true;
    },
    handleCheckSizeChange(e) {
      this.checkList.pageSize = e;
      this.getCheckList();
    },
    handleCheckCurrentChange(e) {
      this.checkList.pageNumber = e;
      this.getCheckList();
    },
    handleClose() {
      this.dialogVisible = false;
      this.createdInfo.time = '';
      this.createdInfo.reason = '';
      this.createdInfo.remark = '';
      this.createdInfo.name = '';
      this.createdInfo.warehouseId = ''
      this.createdInfo.checkVouchers = ''
      this.materialList = [];
    },
    updateStatus(type, info) {
      if (info.checkStatus !== 0) {
        this.$message.error('当前盘点单已处理!');
        return;
      }

      this.$alert(`修改ID为:${info.checkId}盘点单状态`, '提示', {
        confirmButtonText: '确定',
        callback: (res) => {
          if (res === 'confirm') {
            this.$api.checkUpdateStatus(
              {
                type: type,
                checkId: info.checkId,
                warehouseId: info.warehouseId
              }
            ).then(res => {
              this.getCheckList();
            })
          }
        }
      });
    },
    addCheckConfirm() {
      let list = [];
      this.materialList.map(el => {
        if (el.count !== 0 && el.count !== '') {
          el.materialName = el.material.materialName;
          el.price = el.material.price;
          el.salePrice = el.material.salePrice;
          list = list.concat(el)
        }
      })

      if (list.length == 0) {
        this.$message.error('请添加盘点材料!');
        return
      }
      for (let i in this.createdInfo) {
        if (this.createdInfo[i] == '') {
          this.$message.error('请输入盘点单信息!');
          return
        }
      }
      this.createdInfo.time = dayjs(this.createdInfo.time).format("YYYY-MM-DD");
      this.$api.checkCheckAdd({
        checkDetailList: list,
        checkTime: this.createdInfo.time,
        reason: this.createdInfo.reason,
        remark: this.createdInfo.remark,
        checkName: this.createdInfo.name,
        warehouseId: this.createdInfo.warehouseId,
        checkVouchers: this.createdInfo.checkVouchers
      }).then(res => {
        this.createdInfo.time = '';
        this.createdInfo.reason = '';
        this.createdInfo.remark = '';
        this.createdInfo.name = '';
        this.createdInfo.warehouseId = ''
        this.createdInfo.checkVouchers = ''
        this.materialList = [];
        // this.materialList.map(el => {
        //     el.count = 0;
        // })
        this.getCheckList();
        this.dialogVisible = false;
      })
    }

  },
};
</script>

<style lang="less" scoped>
.search {
  display: flex;
  align-items: center;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.mainTable {
  margin: 10px 0;
}

.flex {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 10px;
}

.default /deep/ .el-button {
  border-color: #ff6a00;
  background-color: #ff6a00;
}

.default /deep/ .el-button:hover {
  color: white;
  border-color: #f59a59;
  background-color: #f59a59;
}

/deep/ .el-button:hover {
  color: black;
  border-color: #DCDFE6;
  background-color: white;
}

span /deep/ .el-button:nth-child(2) {
  border-color: #ff6a00;
  background-color: #ff6a00;
}

span /deep/ .el-button:nth-child(2):hover {
  color: white;
  border-color: #f59a59;
  background-color: #f59a59;
}

.createInfo {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 20px
}

.createInfo > div > div:nth-child(1) {
  margin-bottom: 10px;
}

// .main /deep/ .el-select:hover{
//   border-color:#ff6a00 !important;
// }
//  /deep/ .el-input__inner{
//   border-color: #ff6a00 !important;
// }
/deep/ .el-input__inner:hover {
  border-color: #ff6a00 !important;
}

/deep/ .el-input__inner:focus {
  border-color: #ff6a00 !important;
}

/deep/ .selected {
  color: #ff6a00 !important;
}

/deep/ .active {
  color: #ff6a00 !important;
}

/deep/ .selected {
  color: #ff6a00 !important;
}

/deep/ .el-loading-text {
  color: #ff6a00 !important;
}

/deep/ .el-icon-loading {
  color: #ff6a00 !important;
}
</style>
